package RPC.medium;


import RPC.client.Response;
import RPC.handler.param.ServerRequest;
import com.alibaba.fastjson.JSONObject;

import javax.xml.transform.Result;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Media {
    public static  Map<String,BeanMethod> beanMethodMap;
    private static Media m=null;
    private Media(){

    }
    static {
        beanMethodMap= new HashMap<>();
    }

    public static Media newInstance() {
        if(m==null){
         m=new Media();
        }
        return m;
    }

//    反射处理业务代码
    public Response process(ServerRequest request) {
        Response result=null;
        try {
        String command=request.getCommand();
        final BeanMethod beanMethod = beanMethodMap.get(command);
        if(beanMethod==null){
            return null;
        }

        Object bean=beanMethod.getBean();
        final Method m = beanMethod.getMethod();
        final Class<?> parameterType = m.getParameterTypes()[0];
        Object content=request.getContent();
            final Object args = JSONObject.parseObject(JSONObject.toJSONString(content), parameterType);

             result = (Response) m.invoke(bean, args);
             result.setId(request.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
